package com.dongnaoedu.rpc.redis.spring;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 接收响应数据
 * 
 * @author Tony
 *
 */
@Component
public class ConsumerListener implements MessageListener {
	private final Log log = LogFactory.getLog(getClass());
	private final ConcurrentHashMap<String,CompletableFuture> map = new ConcurrentHashMap<>();

	/**
	 * 存放消费者的channel信息
	 */
	public static final ConcurrentHashMap<String, CompletableFuture<Object>> COMPELTABLE_CHANNELS = new ConcurrentHashMap<>();

	@Override
	public void onMessage(Message message, byte[] pattern) {
		log.info("收到一个执行结果：" + new String(message.getBody()));
		JSONObject request = JSONObject.parseObject(new String(message.getBody()));
		String msgId = request.getString("msgId");
		String result = request.getString("data");
		CompletableFuture future = map.get(msgId);
		future.complete(result);
	}

	public void addFuture(String key,CompletableFuture future){
		map.putIfAbsent(key,future);
	}
}
